<template>
	<view class="login_box">
		<view class="text_login">
			<!-- logo -->
			<image class="login_logo"  src="../../static/logo/orange.png" alt="" />
			
			<!-- 表单区域 -->
			<view class="login_phone">
				<text>手机号</text>
				<input type="text"  maxlength="11" v-model="phone" />
			</view>
			<view class="login_code">
				<text>验证码</text>
				<input type="text"  maxlength="4" v-model="code" />
				<view hover-class="touchOpacity" @click="getCode">{{codeText}}</view>
			</view>
			
			<!-- 登录按钮 -->
			<view class="login_but" hover-class="touchOpacity" >
				<text space="ensp" @click="_login">登    录</text> 
			</view>
		</view>
	</view>
</template>

<script>

	export default {
		data() {
			return {
				phone:'',
				code:'',
				codeFlag:false,
				codeText:'获取验证码'
			}
		},
		methods: {
			// 登陆注册
			/* 
				点击登录：如果用户使用的手机号之前没有就是注册，如果手机号之前用过，就是登陆
			 */
			async _login(){
				let phone = this.phone;
				let code = this.code;
				let phoneSt = uni.getStorageSync('phone')
				let codeSt = uni.getStorageSync('code')
				if(phone == '' || phoneSt == '' || phone != phoneSt){
					uni.showToast({
						title:'手机号不正确',
						icon:'error'
					})
					return
				}
				if(code=='' || codeSt == '' || code != codeSt){
					uni.showToast({
						title:'验证码不正确',
						icon:'error'
					})
					return
				}
				let options = {
					url:'/api/smslogin',
					method:'POST',
					data:{phone}
				}
				let res = await this.$http(options);
				if(res.data.code == 200){
					uni.setStorageSync('userinfo',res.data.list)
					this.$store.commit('changeLogin',res.data.list)
					uni.showToast({
						title:res.data.msg,
						icon:'success'
					})
					setTimeout(()=>{
						uni.switchTab({
							url:'../user/user'
						})
					},2000)
				}else{
					uni.showToast({
						title:'注册或登陆失败',
						icon:'error'
					})
				}
				
				console.log(res);
			},
			// 获取验证码
			async getCode(){
				if(this.codeFlag){return false}
				this.codeFlag = true
				let phone = this.phone;
				// let reg = /^1[3-9][0-9]{9}$/
				if(phone == ''){
					uni.showToast({
						title:'手机号不能为空',
						icon:'error'
					})
					return
				}
				let options = {
					url:'/api/sms',
					data:{phone}
				}
				let res = await this.$http(options);
				if(res.data.code == 200){
					let code = res.data.list.code;
					console.log(code);
					uni.setStorageSync('code',code)
					uni.setStorageSync('phone',this.phone)
					let num = 10
					let timer = setInterval(()=>{
						num--;
						this.codeText = num + 's后重新获取'
						if(num<1){
							clearInterval(timer);
							num=10;
							this.codeFlag = false
							this.codeText = '获取验证码'
						}
					},1000)
				}else{
					uni.showToast({
						title:'网络故障~',
						icon:'error'
					})
					this.codeFlag = false  // 请求失败以后还可以重新发送
				}
			}
		}
}
</script>

<style>
	/* 引入样式 */
	@import url("@/static/css/textlogin.css");
</style>
